package org.bot.plugin.web.event;

import com.alibaba.fastjson.JSONObject;
import org.bot.api.event.DataStorage;
import org.bot.api.event.EventName;
import org.bot.api.event.Events;
import org.bot.api.flow.FlowNode;
import org.bot.http.client.HttpTool;
import org.bot.plugin.web.util.CookieBuild;
import org.bot.plugin.web.util.WebApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@EventName("站内POST请求")
public class WebSiteHttpPost implements Events {

    @Autowired
    WebApi webApi;

    @Override
    public Object exec(FlowNode note, DataStorage data) {
        String arg = note.getArg();
        if (arg == null) {
            arg = data.get(note.getDataIndex()).toString();
        }
        boolean validObject = JSONObject.isValidObject(arg);
        if (!validObject) {
            throw new RuntimeException("站内POST请求事件参数错误");
        }
        JSONObject argParam = JSONObject.parseObject(arg);
        String postType = argParam.getString("postType");
        if (postType == null) {
            postType = "form";
        }

        String url = argParam.getString("url");
        if (url == null) {
            throw new RuntimeException("请求地址为空");
        }
        JSONObject params = argParam.getJSONObject("params");
        JSONObject rsp = null;
        switch (postType) {
            case "json":
                rsp = HttpTool.doJsonPost(url, params,
                        CookieBuild.build(webApi.getWebDriver(note)));
                break;
            case "form":
                rsp = HttpTool.doPost(url, params,
                        CookieBuild.build(webApi.getWebDriver(note)));
        }
        return rsp;
    }

}
